package com.foreveross.crawl.common.util;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.PropertyNameProcessor;
import net.sf.json.util.CycleDetectionStrategy;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.foreveross.crawl.common.jpa.annontation.HBaseColumn;

public class JsonUtil {
	
	private final static Logger logger = LoggerFactory.getLogger(JsonUtil.class);
	
	public static Object getDTO(String jsonString) {
		JSONObject jsonObject = null;
		try {
			//	           setDataFormat2JAVA();        
			jsonObject = JSONObject.fromObject(jsonString);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return JSONObject.toBean(jsonObject);
	}
	
	public static Map<String,Object> getMap(InputStream in){
		ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
		Map<String, Object> mapData = null;
		try {
			mapData = mapper.readValue(in, Map.class);
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return mapData;
		
	}

	public static String toJson(List<Object> data) {
		JsonConfig jc = new JsonConfig();
		PropertyNameProcessor namepro = new PropertyNameProcessor() {
			
			@Override
			public String processPropertyName(Class clazz, String key) {
				String name = null;
				HBaseColumn annot = null;
				
				try {
					annot= clazz.getDeclaredField(key).getAnnotation(HBaseColumn.class);
					if(annot != null){
						name = annot.family() + "|" + annot.qualifier();
					}
				} catch (Exception e) {
					e.printStackTrace();
//					logger.error("对象toJson时异常, 处理属性：{}, 处理对象:{}", new Object[]{key, clazz}, e);
				} 
				
				return name;
			}
		};
		
		jc.setExcludes(new String[]{"handler","hibernateLazyInitializer"});  
		jc.setIgnoreDefaultExcludes(false);
		jc.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);  
//		jc.setExcludes(obj);
		
		jc.registerJsonValueProcessor(java.util.Date.class, new JsonValueProcessorImpl());
		jc.registerJsonValueProcessor(java.sql.Date.class, new JsonValueProcessorImpl());
		jc.registerPropertyNameProcessor(data.getClass(), namepro);
		JSONArray jsonArray = new JSONArray();
		
		return jsonArray.fromObject(data, jc).toString();
	}
	
	public static String toJson(Set<Object> data) {
		JsonConfig jc = new JsonConfig();
		PropertyNameProcessor namepro = new PropertyNameProcessor() {
			
			@Override
			public String processPropertyName(Class clazz, String key) {
				String name = null;
				HBaseColumn annot = null;
				
				try {
					annot= clazz.getDeclaredField(key).getAnnotation(HBaseColumn.class);
					if(annot != null){
						name = annot.family() + "|" + annot.qualifier();
					}
				} catch (Exception e) {
					e.printStackTrace();
//					logger.error("对象toJson时异常, 处理属性：{}, 处理对象:{}", new Object[]{key, clazz}, e);
				} 
				
				return name;
			}
		};
		
		jc.setExcludes(new String[]{"handler","hibernateLazyInitializer"});  
		jc.setIgnoreDefaultExcludes(false);
		jc.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);  
//		jc.setExcludes(obj);
		
		jc.registerJsonValueProcessor(java.util.Date.class, new JsonValueProcessorImpl());
		jc.registerJsonValueProcessor(java.sql.Date.class, new JsonValueProcessorImpl());
		jc.registerPropertyNameProcessor(data.getClass(), namepro);
		JSONArray jsonArray = new JSONArray();
		
		return jsonArray.fromObject(data, jc).toString();
	}
	
	public static String toJson(Object data, String[] obj) {
		PropertyNameProcessor namepro = new PropertyNameProcessor() {
			
			public String processPropertyName(Class clazz, String key) {
				HBaseColumn annot = null;
				try {
//					Field field = clazz.getDeclaredField(key);
//					if(field.getType().toString().contains("ReturnDoublePlaneInfoEntity")){
//						Class<?> myself = field.getGenericType().getClass();
//						System.out.println(field + " === " + myself);
//						processPropertyName(myself, key);
//					}
					annot= clazz.getDeclaredField(key).getAnnotation(HBaseColumn.class);
					if(annot != null){
						key = annot.family() + "|" + annot.qualifier();
					}
				} catch(NoSuchFieldException nf) {
					clazz = clazz.getSuperclass();
					key = processPropertyName(clazz, key);
				} catch (Exception e) {
					logger.error("对象toJson时异常, 处理属性：{}, 处理对象:{}", new Object[]{key, clazz}, e);
				} 
				
				return key;
			}
		};
		JsonConfig cfg=new JsonConfig();
		cfg.setExcludes(new String[]{"handler","hibernateLazyInitializer"});  
		cfg.setIgnoreDefaultExcludes(false);
		cfg.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);  
		cfg.setExcludes(obj);
		
		cfg.registerJsonValueProcessor(java.util.Date.class, new JsonValueProcessorImpl());
		cfg.registerJsonValueProcessor(java.sql.Date.class, new JsonValueProcessorImpl());
		cfg.registerJsonPropertyNameProcessor(data.getClass(), namepro);
		
		JSONObject jsonObject = new JSONObject();
		
		return jsonObject.fromObject(data, cfg).toString();
	}
}
